import numpy as np
import csv
import random
from datetime import datetime
from time import strftime


def getCurTime():
    """
    get current time
    Return value of the date string format(%Y-%m-%d %H:%M:%S)
    """
    format='%Y-%m-%d %H:%M:%S'
    sdate = None
    cdate = datetime.now()
    try:
        sdate = cdate.strftime(format)
    except:
        raise ValueError
    return sdate

def build_data_list(inputCSV):
    sKey = []
    fn = inputCSV
    ra = csv.DictReader(file(fn), dialect="excel")
    
    for record in ra:
        #print record[ra.fieldnames[0]], type(record[ra.fieldnames[-1]])
        for item in ra.fieldnames:
            temp = float(record[item])
            sKey.append(temp)
    sKey = np.array(sKey)
    sKey.shape=(-1,len(ra.fieldnames))
    return sKey

def cal_dis(id1, id2, coordinate):
    temp_dis = (coordinate[int(id1), 0] - coordinate[int(id2), 0])**2
    temp_dis += (coordinate[int(id1), 1] - coordinate[int(id2), 1])**2
    temp_dis = temp_dis**0.5
    return temp_dis

#--------------------------------------------------------------------------
#MAIN

if __name__ == "__main__":
    print "========================================"
    print "begin at " + getCurTime()
    caseCSV = 'C:/_DATA/CancerData/SatScan/neast_id_geo.csv'
    dataMatrix = build_data_list(caseCSV)
    #dataMatrix = dataMatrix[np.argsort(dataMatrix[:,0]),:]
    dataMatrix = dataMatrix[:,1:]
    mixed = [91,98,101,104,114,115,119,126,131,142,146,147,154,162,168,172]
    rural = [8,9,10,11,12,13,14,15,17,19,20,26,28,33,34,37]
    urban = [105,107,112,120,122,125,127,128,130,133,134,141,143,149,152,155]

    hot_1 = [9,130,147]
    hot_2 = hot_1 + [10,133,154]
    hot_4 = hot_2 + [12,17,125,131,141,146]
    hot_8 = hot_4 + [14,19,20,26,114,115,119,120,128,134,149,168]
    hot_16 = mixed + rural + urban

    useddata = urban
    dis = []
    for item in useddata:
        dis.append(cal_dis(130, item, dataMatrix))
    #print dis
    output = np.append(useddata, dis)
    #print output
    output = np.array(output)
    output.shape = (2,-1)
    output = np.transpose(output)
    output = output[np.argsort(output[:,1]),:]
    print output[:,0]
        